package com.hcb.service.impl;

import com.hcb.mapper.MessageMapper;
import com.hcb.mapper.UserMapper;
import com.hcb.pojo.Message;
import com.hcb.pojo.User;
import com.hcb.service.MessageService;
import com.hcb.utils.TimeUtils;
import com.hcb.utils.Websocket;
import com.hcb.vo.ChartVo;
import com.hcb.vo.MessageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    MessageMapper messageMapper;
    @Autowired
    UserMapper userMapper;
    //消息列表
    @Override
    public List<MessageVo> getMessagesList(Integer userId) {
        //获取与当前用户聊天的用户id
        List<Integer> userIds=messageMapper.getUsersId(userId);
        //获取最新的消息
        List<MessageVo> messageVoList=new ArrayList<>();
        userIds.forEach(id->{
            MessageVo messageVo=new MessageVo();
            Message message=messageMapper.getMessagesListItem(userId,id);
            messageVo.setUserId(id);
            User user=userMapper.selectById(id);
            messageVo.setUsername(user.getName());
            messageVo.setImgUrl(user.getImgUrl());
            toVo(messageVo,message);
            messageVoList.add(messageVo);
        });
        return messageVoList;
    }

    @Override
    public List<ChartVo> getChartList(Integer userId, Integer userId2) {
       List<Message> messageList=messageMapper.getMessageList(userId,userId2);
       List<ChartVo> chartVoList=new ArrayList<>();
       messageList.forEach(message -> {
           ChartVo chartVo=new ChartVo();
           chartVo.setMessage(message.getMessage());
           chartVo.setDate(TimeUtils.formatDate(message.getDate()));
           User user=userMapper.selectById(message.getUserFrom());
           chartVo.setImgUrl(user.getImgUrl());
           chartVo.setPosition(message.getUserFrom()==userId?1:0);
           chartVoList.add(chartVo);
       });
       return chartVoList;
    }

    @Override
    public void sendMessage(Message message) {
        Map<String,String> m=new HashMap<>();
        Timestamp timestamp=new Timestamp(System.currentTimeMillis());
        m.put("message", message.getMessage());
        m.put("date",TimeUtils.formatDate(timestamp));
        m.put("position","0");
        m.put("imgUrl",userMapper.selectById(message.getUserFrom()).getImgUrl());
        Websocket.sendOneMessage(message.getUserTo().toString(),m);
        message.setDate(timestamp);
        messageMapper.insert(message);
    }


    public void toVo(MessageVo messageVo,Message message){
        messageVo.setMessage(message.getMessage());
        messageVo.setDate(TimeUtils.formatDate(message.getDate()));
    }
}
